import {
  FormControl,
  FormControlProps,
  FormLabel,
  FormLabelProps,
  Select,
  SelectProps,
  Tooltip,
  TooltipProps,
} from '@chakra-ui/react';
import { memo, MouseEvent } from 'react';

import IAIOption from './IAIOption';

type IAISelectProps = SelectProps & {
  formControlProps?: FormControlProps;
  formLabelProps?: FormLabelProps;
  feature?: any;
  label?: string;
  tooltip?: string;
  tooltipProps?: Omit<TooltipProps, 'children'>;
  validValues:
    | Array<number | string>
    | Array<{ key: string; value: string | number }>;
};
/**
 * Customized Chakra FormControl + Select multi-part component.
 */
const IAISelect = (props: IAISelectProps) => {
  const {
    label,
    isDisabled,
    validValues,
    formLabelProps,
    formControlProps,
    tooltip,
    tooltipProps,
    feature,
    ...rest
  } = props;
  return (
    <Tooltip label={tooltip} {...tooltipProps}>
      <FormControl
        isDisabled={isDisabled}
        {...formControlProps}
        onClick={(e: MouseEvent<HTMLDivElement>) => {
          e.stopPropagation();
          e.nativeEvent.stopImmediatePropagation();
          e.nativeEvent.stopPropagation();
          e.nativeEvent.cancelBubble = true;
        }}
      >
        {label && <FormLabel {...formLabelProps}>{label}</FormLabel>}
        <Select {...rest}>
          {validValues.map((opt) => {
            return typeof opt === 'string' || typeof opt === 'number' ? (
              <IAIOption key={opt} value={opt}>
                {opt}
              </IAIOption>
            ) : (
              <IAIOption key={opt.value} value={opt.value}>
                {opt.key}
              </IAIOption>
            );
          })}
        </Select>
      </FormControl>
    </Tooltip>
  );
};

export default memo(IAISelect);
